package com.wss.controller;

import com.alibaba.fastjson.JSON;
import com.wss.domain.Account;
import com.wss.domain.Message;
import com.wss.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @RequestMapping(value="/registerUser", method= RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String registerUser(Account account, HttpServletRequest request, HttpServletResponse response){
        System.out.println("==============进入到/registerUser=============");
        String username = account.getUsername();
        // 查询此用户名是否已注册
        boolean userRegistered = registerService.checkUsername(username);
        // 返回给前端的信息对象
        Message message = new Message();
        String msg = "";
        if (!userRegistered){
            // 添加一个普通用户权限
            account.setP_id(2);
            // 执行用户注册方法
            boolean regSuccess = registerService.registerAccount(account);
            if (regSuccess){
                // 将account对象存入session
                HttpSession session = request.getSession();
                session.setAttribute("Account", account);
                message.setResCode(1);
                message.setResultMsg("注册成功");
            }else{
                message.setResCode(0);
                message.setResultMsg("注册失败");
            }
        }else{
            message.setResCode(0);
            message.setResultMsg("用户名已存在");
        }
        msg = JSON.toJSONString(message);
        return msg;
    }
}
